package com.ajk.server.bkcontroller;

import java.security.Principal;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ajk.server.controller.access.ArgIndexForPrintLog;
import com.ajk.server.controller.events.RemoteSyncEvent;
import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.CreditsHistory;
import com.ajk.server.model.TreeMenu;
import com.ajk.server.model.Users;
import com.ajk.server.model.query.CreditsHistoryQuery;
import com.ajk.server.model.query.TreeMenuQuery;
import com.ajk.server.model.query.UsersQuery;
import com.ajk.server.model.request.UserReq;
import com.ajk.server.model.response.Result;
import com.ajk.server.model.response.ResultList;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.model.response.UserRes;
import com.ajk.server.security.AjkUserDetails;
import com.ajk.server.service.CreditsHistoryService;
import com.ajk.server.service.SuggestService;
import com.ajk.server.service.TreeMenuService;
import com.ajk.server.service.UsersService;
import com.ajk.server.utils.AjkUtil;
import com.ajk.server.utils.FileStoreUtil;
import com.ajk.server.utils.MD5Tools;
import com.ajk.server.utils.SpringContextUtil;

@RestController
@RequestMapping("/admin/users")
public class AdminUserController {


	@Autowired
	UsersService usersService;

	@Autowired
	SuggestService suggestService;
	
	@Autowired
	TreeMenuService treeMenuService;
	
	@Autowired
	CreditsHistoryService creditsHistoryService;

	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResultList<Users> listUserProfile(UsersQuery query){
		ResultList<Users> result = new ResultList<>();
		List<Users> userRes = usersService.findUsersByQuery(query);
		result.setItemList(userRes);
		Integer count =  usersService.countUsersByQuery(query);
		
		if (CollectionUtils.isNotEmpty(userRes)) {
			for (Users users : userRes) {
				//拉取菜单
				Integer userId = users.getId();
				TreeMenuQuery query1 = new TreeMenuQuery();
				query1.setLimit(0);
				query1.setUserId(userId);
				
				List<TreeMenu> list = treeMenuService.findTreeMenuByQuery(query1);
				users.setMenuList(list);
			}
		}
		
		query.setCount(count);
		result.setExt(query);
		return result;
	}

	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/findOne/{userId}", method = RequestMethod.GET)
	public ResultObject<UserRes> findMyProfile(@PathVariable("userId") Integer userId){
		UserRes userRes = usersService.findUsersById(userId);
		return new ResultObject<>(userRes);
	}
	
	/**
	 * 阳光值记录列表
	 */
	@ArgIndexForPrintLog(indexes = { 1 })
	@RequestMapping(value = "/{userId}/credits/list", method = RequestMethod.GET)
	public ResultList<CreditsHistory> findMyCredits(@PathVariable("userId") Integer userId,CreditsHistoryQuery query,Principal principal) {
		query.setUserId(userId);
		List<CreditsHistory> list = creditsHistoryService.findCreditsHistoryByQuery(query);
		ResultList<CreditsHistory> result =  new ResultList<CreditsHistory>(list);
		Integer count = creditsHistoryService.countCreditsHistoryByQuery(query);
		query.setCount(count);
		result.setExt(query);
		return result;
	}
	
	/**
 	*新增 用户表
 	*/
	@ArgIndexForPrintLog(indexes = { 0 })
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> insertUsers(@RequestBody Users domain){
		String originPwd = domain.getPassword();
		String password = MD5Tools.MD5(originPwd);
		domain.setPassword(password);
		Integer idInteger = usersService.insertUsers(domain);
		return new ResultObject<Integer>(idInteger);
 	}
 
 	
 	/**
 	*更新 用户表
 	*/
	@ArgIndexForPrintLog(indexes = { 0 })
	@RequestMapping(value = "/modify", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> updateUsers(@RequestBody UserReq myProfile){
 		myProfile.setPassword(null);
		Integer idInteger = usersService.updateUsers(myProfile);
		return new ResultObject<Integer>(idInteger);
 	}
 	
	@ArgIndexForPrintLog(indexes = { 0 })
	@RequestMapping(value = "/reset_password/{userId}", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> resetPassword(@RequestBody UserReq myProfile,@PathVariable("userId") Integer userId){
		String originPwd = myProfile.getPassword();
		String password = MD5Tools.MD5(originPwd);
		UserReq req = new UserReq();
		req.setId(userId);
		req.setPassword(password);
		
		Integer idInteger = usersService.updateUsers(myProfile);
		return new ResultObject<Integer>(idInteger);
 	}
	
	/**
	 *用户修改头像
	 */
	@ArgIndexForPrintLog(indexes={1})
	@RequestMapping(value = "/avatar/{userId}", method = RequestMethod.POST,consumes="multipart/form-data")
	public Result updateAvatar(MultipartFile avatarFile,@PathVariable("userId") Integer userId){
		if(avatarFile!=null && avatarFile.getSize()>0){
			if (avatarFile.getSize() > 2097152) {
				throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "头像太大,请选择小于2兆的头像上传");
			}
			String fileDbName = FileStoreUtil.storeFile(avatarFile, "avatar");
			UserReq users = new UserReq();
			users.setId(userId);
			users.setAvatar(fileDbName);
			usersService.updateUsers(users);
			
			RemoteSyncEvent event = new RemoteSyncEvent(userId, RemoteSyncEvent.SYNC_USER);
			SpringContextUtil.getApplicationContext().publishEvent(event);
		} else {
			// 文件传输失败。抛异常
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "头像传输失败！请重试");
		}
		return new Result();
	}
}
